package com.sword.onlysword.config;

import com.baomidou.mybatisplus.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

/**
 * com.sword.onlysword.config.MybatisDB2
 * Created by SwordLiu on 2018-03-08.
 */
@Configuration
@MapperScan(basePackages = "com.sword.onlysword.mapper2*", sqlSessionTemplateRef = "template2")
public class MybatisDB2 {

    @Value("${mybatis-plus.mapper-locations}")
    private String mapperLocations;
    @Value("${mybatis-plus.typeAliasesPackage}")
    private String aliasesPackage;

    @Autowired
    @Qualifier("db2")
    private DataSource db2;

    @Bean
    public SqlSessionFactory sessionFactory2() throws Exception {
        /*该 MybatisSqlSessionFactoryBean 为 baomidou 插件实现，拥有通用mapper实现 */
        MybatisSqlSessionFactoryBean factoryBean = new MybatisSqlSessionFactoryBean();
        /*该SqlSessionFactoryBean为mybatis实现，不包含插件
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();*/
        /*注入baomidou分页插件*/
        factoryBean.setPlugins(new Interceptor[]{new PaginationInterceptor()});
        factoryBean.setDataSource(db2);
        factoryBean.setTypeAliasesPackage(aliasesPackage);
        factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(mapperLocations));

        return factoryBean.getObject();
    }

    @Bean
    public SqlSessionTemplate template2() throws Exception {
        return new SqlSessionTemplate(sessionFactory2());
    }

}
